package com.spring.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author Spring King
 * @date 2021/7/10
 */
public class StaticResourceUtil {

    private StaticResourceUtil() {
    }

    public static String getAbPath(String path) {
        URL url = StaticResourceUtil.class.getResource("/");
        if (url == null) {
            throw new IllegalArgumentException("Illegal path");
        }
        return url.getPath().replaceAll("\\\\", "/") + path;
    }

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        // 输出HTTP请求头，然后再输出其他内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes(StandardCharsets.UTF_8));
        long written = 0;
        int cacheByteSize = 1024;
        byte[] bytes = new byte[cacheByteSize];

        while (written < resourceSize) {
            // 当剩余未读取内容长度小于1024，直接读取
            if (written + cacheByteSize > resourceSize) {
                cacheByteSize = (int) (resourceSize - written); //剩余文件长度
                bytes = new byte[cacheByteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += cacheByteSize;
        }
    }
}
